#include <glib.h>

#define SIZE       5
#define NUMBER_MIN 100
#define NUMBER_MAX 200

static guint32 array[SIZE];

typedef struct mydata_tag {
    int id;
    char *name;
}my_data_t;

void my_struct_free_func(gpointer data)
{
    my_data_t *mydata = NULL;
    mydata = (my_data_t *)data;

    if(NULL != mydata->name) {
    	//g_printf("free mydata->name: %s \n", mydata->name);
    	free(mydata->name);
    }

    return;
}

void my_struct_printf(gpointer data, gpointer user_data)
{
    g_printf("%s: id=%d, name=%s, user_data=%s\n", __FUNCTION__, 
        ((my_data_t *)data)->id, ((my_data_t *)data)->name, (char *)user_data);
}

gint my_int_cmp_func (gconstpointer d1, gconstpointer d2)
{
    gint i1, i2;

    i1 = GPOINTER_TO_INT (d1);
    i2 = GPOINTER_TO_INT (d2);

    return i1 - i2;
}

gint my_struct_cmp_func (gconstpointer d1, gconstpointer d2)
{
    return ((my_data_t *)d1)->id - ((my_data_t *)d2)->id;
}

static void test_slist_sort_struct(void)
{
    gint i = 0;
    GSList *slist = NULL;
    my_data_t mydata[16];
    char name[16] = {0};

    memset(mydata, 0, sizeof(my_data_t)*SIZE);
    for(i=0;i<SIZE;i++) {
        mydata[i].id = array[i];
        g_snprintf(name, 16, "data is %d", array[i]);
        mydata[i].name = strdup(name);
        slist = g_slist_append(slist,  (gpointer)&mydata[i]);
    }

    g_print("\n");
    g_print("len=%d \n", g_slist_length(slist));
    g_slist_foreach(slist, my_struct_printf, "before sort");

    slist = g_slist_sort(slist, my_struct_cmp_func);
    g_slist_foreach(slist, my_struct_printf, "after sort");

    g_slist_free_full(slist, my_struct_free_func);
}

gint main (gint argc, gchar *argv[])
{
    gint i;

    g_test_init (&argc, &argv, NULL);

    for (i = 0; i < SIZE; i++) {
        array[i] = g_test_rand_int_range (NUMBER_MIN, NUMBER_MAX);
    }

    g_test_add_func ("/slist/sort_struct", test_slist_sort_struct);

    return g_test_run ();
}
